package com.github.tommas.admintpl.security;

import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.util.StringUtils;

public class UserPrincipal {
    private final String username;
    private final int userId;

    public UserPrincipal(String username, int userId) {
        this.username = username;
        this.userId = userId;
    }

    public String getUsername() {
        return username;
    }

    public int getUserId() {
        return userId;
    }

    public static UserPrincipal fromPrincipalCollection(PrincipalCollection pc) {
        String username = pc.oneByType(String.class);
        if (!StringUtils.hasLength(username)) {
            throw new RuntimeException(String.format("Cannot find username in principal collection: %s", pc));
        }
        Integer userId = pc.oneByType(Integer.class);
        if (userId == null) {
            throw new RuntimeException(String.format("Cannot find user id in principal collection: %s", pc));
        }

        return new UserPrincipal(username, userId);
    }
}
